var isLoadingAllData = true;//标识当前是不是在加载全部数据
var isClickExportBtn = false;//标识当前是不是点击了导出按钮
//请求全部数据getSimpleSampleBases
$.ajax({
    method: 'POST',
    url: '/csfy/intf.do?method=getExportSampleBases',
    success: function (res) {
        isLoadingAllData = false
        if (res && res.code && res.code == 200) {
            dataList = res.rows
            if(isClickExportBtn) {
                flag = true
                isClickExportBtn = false
                $("#fountainTextG").show()
                setTimeout(() => {
                    exportSampleExcel(dataList)
                }, 0)
                handleLoading()
            }
        }
    },
    error: function (err) {
        isLoadingAllData = false
    }
})
//总条目
var total = 0;
//总数据列表
var dataList = null;
var exportTimer = null;
function handleLoading() {
    exportTimer && window.clearInterval(exportTimer)
    exportTimer = null
    exportTimer = setInterval(() => {
        if (window.sessionStorage.getItem('exportFinished')) {
        flag = false
        $("#fountainTextG").hide()
        window.sessionStorage.removeItem('exportFinished')
        exportTimer && window.clearInterval(exportTimer)
        exportTimer = null
        isClickExportBtn = false
    }
}, 1000)
}

//区县列表getAddrs
$.ajax({
    method: 'POST',
    url: '/csfy/intf.do',
    data: { method: 'getAddrsToAccess', parentId: 4301 },
    success: function (res) {
        var options = '<option value="">请选择</option>'
        if (res && res.code == 200) {
            (res.rows || []).forEach(countryItem => {
                options += '<option value="' + countryItem.name + '">' + countryItem.name + '</option>';
        })
        }
        $('#search-country').html(options);
    }
});

$(function () {
    //街道getTown
    $('#search-country').change(function () {
        var countryStr = $(this).val();//获得区县
        $.ajax({
            method: 'POST',
            url: '/csfy/intf.do',
            data: { method: 'getTownToUserAccess', name: countryStr },
            success: function (res) {
                var options = '<option value="">请选择</option>'
                if (res && res.code == 200) {
                    (res.rows || []).forEach(countryItem => {
                        options += '<option value="' + countryItem.name + '">' + countryItem.name + '</option>';
                })
                }
                $('#search-town').html(options);
            }
        });
    });
});

//医院列表
$.ajax({
    method: 'POST',
    url: '/csfy/intf.do',
    data: {
        method: 'getCustomers',
        addressCity: '长沙市',
    },
    success: function (res) {
        if (res && res.code == 200) {
            var customerList = res.rows || [];
            var customerOptions = '<option value="">请选择医院</option>';
            customerList.forEach(customer => {
                customerOptions += '<option value="' + customer.customerCode + '">' + customer.customerName + '<option>';
        });
            $('#search-customer').html(customerOptions);
            //$("#search-customer option[value='34']").removeAttr("selected");//默认选中长沙市妇幼保健院
        }
    }
});

var flag = false
// 导出表格
function exportTable() {
    var rows = $('#sampleImport_mainTable').datagrid('getSelections');
    if (rows.length > 0) {
        exportSampleExcel(rows)
    } else {
        if (flag) {
            return false
        }
        flag = true
        isClickExportBtn = true
        $("#fountainTextG").show()
        if (dataList && dataList.length && dataList.length == total) {
            setTimeout(() => {
                exportSampleExcel(dataList)
            }, 0)
            handleLoading()
            return false
        }

        //
        if(!isLoadingAllData){
            $.ajax({
                method: 'POST',
                // url: '/csfy/intf.do?method=getSimpleSampleBases',
                url: '/csfy/intf.do?method=getExportSampleBases',
                success: function (res) {
                    if (res && res.code && res.code == 200) {
                        dataList = res.rows
                        setTimeout(() => {
                            exportSampleExcel(dataList)
                        }, 0)
                        handleLoading()
                    } else {
                        flag = false
                        $("#fountainTextG").hide()
                        isClickExportBtn = false
                    }
                },
                error: function (err) {
                    flag = false
                    $("#fountainTextG").hide()
                    isClickExportBtn = false
                }
            })
        }
    }
}
$(".maincontent").height($("body").height() - 50);
//获取搜索条件
function getQueryParams() {
    var sampleName = $("#sampleName").val();//姓名
    var connectPhone = $("#connectPhone").val();//联系电话
    var searchResult = $("#result").val();//检测结果
    var customerCode = $("#search-customer").val();//送检医院
    var country = $("#search-country").val();//区县
    var town = $("#search-town").val();//街道
    var idCard = $("#search-idcard").val();//身份证号码
    var productCode = $("#search-product").val();//产品
    var scanStartTime = $("#search-scan-start-time").val();//开始扫码采样日期
    var scanEndTime = $("#search-scan-end-time").val();//结束扫码采样日期

    var params = {};
    if (sampleName) {
        params.sampleName = sampleName;
    }
    if (connectPhone) {
        params.connectPhone = connectPhone;
    }
    if (searchResult) {
        params.searchResult = searchResult;
    }
    if (customerCode) {
        params.customerCode = customerCode;
    }
    if (country) {
        params.addressCounty = country;
    }
    if (town) {
        params.addressTown = town;
    }
    if (idCard) {
        params.idCard = idCard;
    }
    if (productCode) {
        params.productCode = productCode;
    }
    if (scanStartTime) {
        params.useStartTime = scanStartTime;
    }
    if (scanEndTime) {
        params.useEndTime = scanEndTime;
    }
    return params;
}
//重置刷新
function toRefresh() {
    $("#sampleName").val('');//姓名
    $("#connectPhone").val('');//联系电话
    $("#result").val('');//检测结果
    $("#search-customer").val('');//送检医院
    $("#search-country").val('');//区县
    $("#search-steet").val('');//街道
    $("#search-idcard").val('');//身份证号码
    $("#search-product").val('');//产品
    $("#search-scan-start-time").val('');//开始扫码采样日期
    $("#search-scan-end-time").val('');//结束扫码采样日期
    $("#sampleImport_mainTable").datagrid("reload", {});
}
//按条件搜索
function toSearch() {
    $('#sampleImport_mainTable').datagrid('reload', getQueryParams());
}
//退出登录
function logout() {
    $.ajax({
        url: '/csfy/dologout.do',
        method: 'POST',
        success: function (res) {
            if (JSON.parse(res).code == 200) {
                window.location.href = "/csfy/index.do"
            }
        }
    })
}
//获取当前登录用户信息
$(document).ready(function () {
    $.ajax({
        method: 'POST',
        url: '/csfy/intf.do',
        data: { method: 'getLoginUserInfo' },
        success: res => {
        if (res.code == 10086) {
        //  window.location.href = "/csfy/index.do"
        alert("请重新登录！");
    } else {
        if (res.code == 200) {
            $(".username").html(res.rows.userName);
        }
    }
}
})
})

function showStatus(value, row) {
    if (value == 1) {
        value = "已采样";
    } else {
        value = '';
    }
    return value;
}

function showText(value, row) {
    var step = row.step;
    if (step != null && step != '') {
        if (step.indexOf("1") == 3 && (value == null || value == '')) {
            value = "请查看报告！";
        } else if (step.indexOf("1") != 3 && value != null && value != '') {
            value = '';
        }
    }
    return value;
}

function changeStatus(value, row) {
    // 0未确认，1已确认
    if (value == "0") {
        value = "<image src='resources/images/icons/yes.png'/>";
    }
    if (value == "1") {
        value = "<image src='resources/images/icons/stop.png'/>";
    }
    return value;
}

function changeExpressStatus(value, row) {
    // 0 否 1是
    if (value == "0") {
        return "否";
    }
    if (value == "1") {
        return "是";
    }
    return value;
}

function changeIDCard(value, row) {
    if (row.idCardType == '0') {
        return value;
    } else {
        return '';
    }
}

function changeSys(value, row) {
    if (value == "0") {
        return "本系统";
    }
    if (value == "01") {
        return "SIMS推送";
    }
    return value;
}

function showTemplate(value, row) {
    if (value == '1') return '有';
    if (value == '0') return '无';
    return value;
}

//编辑页面的跳转方法
function toDetail(obj) {
    var sampleId=obj[0];
    var productCode=obj[1];
    var idCard=obj[2];
    var rowJson = '';
    $.ajax({
        method: 'POST',
        async:false,
        url: '/csfy/intf.do?method=getExportSampleBases&sampleBaseId='+ sampleId +'&productCode='+ productCode+'&idCard='+idCard,
        success: function (res) {
            console.log(res);
        if (res && res.code && res.code == 200) {
            rowJson = JSON.stringify(res.rows).replace(/\[/g,'').replace(/\]/g,'');
           }
        }
    });

    var row = JSON.parse(rowJson)
    if (row) {
        var file;
        if (row.fileVer == 'temp/deaf.jsp') {
            file = 'deaf.jsp';
        } else if (row.fileVer == 'temp/diping.jsp') {
            file = 'dipin.jsp';
        } else if (row.fileVer == 'temp/akxChildGenTest.jsp') {
            file = 'akxChildGenTest.jsp';
        } else if (row.fileVer == 'temp/HPV.jsp') {
            file = 'HPV.jsp';
        } else if (row.fileVer == 'temp/Nifty.jsp') {
            file = 'nifty.html';
        } else if (row.fileVer == 'temp/sample1.jsp') {
            file = 'sample1.html';
        } else if (row.fileVer == 'temp/sample2.jsp') {
            file = 'sample2.html';
        }
        if (file) {
            sessionStorage.setItem("sampleInfos", JSON.stringify(row));
            window.location.href = 'static/manage-sys/add-sample/add-sample.html?file=' + file + '&edit=true';
        }
    }
}

//删除页面未采样数据记录
function toDelete(sampleId){
    var isDelete = confirm("您确定要删除这条送检单吗？删除后将无法恢复，请谨慎操作！");

    if(isDelete == true){

    $.ajax({
        method: 'POST',
        async:false,
        url: '/csfy/intf.do?method=deleteExportSampleBases&sampleBaseId='+ sampleId ,
        success: function (res) {
            console.log(res);
            if (res && res.code && res.code == 200) {
                alert("删除成功！");
                window.location.href = 'static/manage-sys/add-sample/sample-list.jsp';
                //alert("删除成功！");
               // rowJson = JSON.stringify(res.rows).replace(/\[/g,'').replace(/\]/g,'');
            }
        }
    })
    }
    else{
        alert("已取消");
        return false;
    };
}

function showEdit(value, row) {
    if (row.sampleStatus != 1) {
        //console.log(row);
        return '<a class="sample-edit" href="javascript:toDetail(\'' + JSON.stringify(row) + '\')"  style="color:#337ab7">编辑</a>';

    }
}


function formatCardId(value, row) {
    var cardId = row.idCard + '-';
    return cardId
}


$('#sampleImport_mainTable').datagrid({
    url: '/csfy/intf.do?method=getExportSampleBases',
    fit: true,
    rownumbers: true,
    pagination: true,
    singleSelect: false,
    striped: true,
    fitColumns: false,
    frozenColumns:
        [[
            { field: 'ck', checkbox: 'true' }
        ]],
    columns: [[
        { field: 'sampleInfoId', hidden: true },
        { field: 'sampleNum', hidden: true },
        { field: 'sampleName', title: '姓名', width: 120, align: 'center' },
        { field: 'editAttribute', title: '操作', width: 120, align: 'center', formatter: showEdit },
        { field: 'customerName', title: '客户名称', width: 150, align: 'center' },
        { field: 'sampleStatus', title: '样品状态', width: 100, align: 'center', formatter: showStatus },
        { field: 'couponNum', title: '免费券编码', width: 120, align: 'center' },
        { field: 'productName', title: '产品名称', width: 250, align: 'center' },
        { field: 'address', title: '联系地址', width: 250, align: 'center' },
        { field: 'familyAddress', title: '常住地址', width: 120, align: 'center' },
        { field: 'addressCounty', title: '区/县', width: 120, align: 'center' },
        { field: 'addressTown', title: '街道', width: 120, align: 'center' },
        { field: 'age', title: '年龄', width: 50, align: 'center' },
        { field: 'idCard', title: '身份证号', width: 150, align: 'center', formatter: formatCardId },
        { field: 'usedTime', title: '扫码时间', width: 120, align: 'center' },
        { field: 'transfusionDate', title: '采样时间', width: 120, align: 'center' },
        { field: 'createTime', title: '录入时间', width: 120, align: 'center' },
        { field: 'lastModifiedUser', title: '最后修改人', width: 200, align: 'center' },
        { field: 'lastModifiedTime', title: '最后修改时间', width: 120, align: 'center' }
    ]],
    onLoadSuccess: function (data) {
        total = data.total
    }
});